/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.games.esmi.ieat.indicatorvalues;

import com.vaadin.ui.Tree;
import eu.games.esmi.ieat.indicatorvalues.data.EMF;
import it.polimi.games.epkb.controller.GpiKpiInstanceJpaController;
import it.polimi.games.epkb.controller.GpiKpiJpaController;
import it.polimi.games.epkb.controller.ServerJpaController;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.epkb.entityClasses.GpiKpiInstance;
import it.polimi.games.epkb.entityClasses.Server;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author user
 */
public class IndicatorTreeGenerator {

    public final static int INDICATOR_TREE = 1;
    public final static int SYSTEM_TREE = 2;
    public final static int APPLICATION_TREE = 3;

    public IndicatorTreeGenerator() {
    }

    public Tree createTree(int type) {

        Tree resultingTree = null;

        switch (type) {

            case 1:
                resultingTree = createIndicatorTree();
                break;
            case 2:
                resultingTree = createSystemTree();
                break;
            case 3:
                resultingTree = createApplicationTree();
                break;

        }
        resultingTree.addStyleName("indicatorTree");
        return resultingTree;

    }

    private Tree createIndicatorTree() {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        Tree tree = new Tree("Indicators");
        tree.setMultiSelect(true);

        String[] indicatorclasses = {"IT Resource Usage", "Application lifecycle", "Energy impact", "Organizational"};


        for (int i = 0; i < indicatorclasses.length; i++) {

            String classe = indicatorclasses[i];

            tree.addItem(classe);
            tree.setChildrenAllowed(classe, true);

            EntityManager em = emf.createEntityManager();
            Query q = em.createQuery("SELECT g FROM GpiKpi g WHERE g.indicatorClassification = :classe");
            q.setParameter("classe", classe);

            List<GpiKpi> indicators = q.getResultList();

            for (GpiKpi indicator : indicators) {

                tree.addItem(indicator.getId() + "-avg");
                tree.setItemCaption(indicator.getId() + "-avg", indicator.getName());
                tree.setParent(indicator.getId() + "-avg", classe);
                tree.setChildrenAllowed(indicator.getId() + "-avg", true);


                Query queryInstances = em.createQuery("SELECT i FROM GpiKpiInstance i WHERE i.idGPIKPI = :indicator");
                queryInstances.setParameter("indicator", indicator);
                List<GpiKpiInstance> instances = queryInstances.getResultList();

                for (GpiKpiInstance instance : instances) {

                    tree.addItem(indicator.getId() + "-" + instance.getIdComponent().getId());
                    tree.setItemCaption(indicator.getId() + "-" + instance.getIdComponent().getId(), instance.getIdComponent().getId());
                    tree.setParent(indicator.getId() + "-" + instance.getIdComponent().getId(), indicator.getId() + "-avg");
                    tree.setChildrenAllowed(indicator.getId() + "-" + instance.getIdComponent().getId(), false);

                }



            }
            tree.expandItemsRecursively(classe);

        }

        // Set multiselect mode
        tree.setMultiSelect(true);
        tree.setImmediate(true);

        emf.close();

        return tree;
    }

    private Tree createSystemTree(String old) {

        String[][] correspondencies = {{"Infrastructural", "server", "rack"}, {"Application", "business_process", ""}};

        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        GpiKpiJpaController indicatorsCtrl = new GpiKpiJpaController(emf);
        GpiKpiInstanceJpaController instanceCtrl = new GpiKpiInstanceJpaController(emf);

        List<GpiKpi> indicators = indicatorsCtrl.findGpiKpiEntities();

        Tree tree = new Tree("System");

        for (GpiKpi indicator : indicators) {


            tree.addItem(indicator.getId());
            tree.setItemCaption(indicator.getId(), indicator.getName());
            tree.setChildrenAllowed(indicator.getId(), true);


            ServerJpaController serverCtrl = new ServerJpaController(emf);
            List<Server> servers = serverCtrl.findServerEntities();

            boolean found = false;
            int i = 0;
            while (!found && i < correspondencies.length) {

                found = indicator.getArchitecturalLayer().equalsIgnoreCase(correspondencies[i][0]);
                i++;

            }

            if (correspondencies[i][0].equalsIgnoreCase("Infrastructural")) {

                for (Server server : servers) {

                    tree.addItem(indicator.getId() + "-" + server.getId());
                    tree.setItemCaption(indicator.getId() + "-" + server.getId(), server.getId());
                    tree.setParent(indicator.getId() + "-" + server.getId(), indicator.getId());
                    tree.setChildrenAllowed(indicator.getId() + "-" + server.getId(), true);

                }

                EntityManager em = emf.createEntityManager();

                Query q = em.createQuery("SELECT i from GpiKpiInstance i WHERE i.idGPIKPI = :indicator");
                q.setParameter("indicator", indicator);
                List<GpiKpiInstance> instances = q.getResultList();

                for (GpiKpiInstance instance : instances) {


                    System.out.println("pippo " + indicator.getId() + " - " + instance.getIdComponent().getCategory());



                    tree.addItem(indicator.getId() + "-" + instance.getIdComponent().getId());
                    tree.setItemCaption(indicator.getId() + "-" + instance.getIdComponent().getId(), instance.getIdComponent().getId());
                    tree.setParent(indicator.getId() + "-" + instance.getIdComponent().getId(), indicator.getId());
                    tree.setChildrenAllowed(indicator.getId() + "-" + instance.getIdComponent().getId(), false);

                }



                em.close();
            }

        }

        // Set multiselect mode
        tree.setMultiSelect(
                true);
        tree.setImmediate(
                true);

        emf.close();

        return tree;
    }

    
    private Tree createApplicationTree() {
/**
        Tree tree = new Tree("Application");

        for (int i = 0; i < 3; i++) {
            String classe = "service " + i;
            tree.addItem(classe);
            tree.setChildrenAllowed(classe, true);
            for (int j = 0; j < 4; j++) {
                String indicator = "indicator " + i + "," + j;
                tree.addItem(indicator);
                tree.setParent(indicator, classe);
            }
            tree.expandItemsRecursively(classe);
        }
        // Set multiselect mode
        tree.setMultiSelect(true);
        tree.setImmediate(true);
        return tree;
**/
   
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        Tree tree = new Tree("Applications");
        tree.setMultiSelect(true);

        // get components list from epkb
        
        //String[] componentsId = {"IT Resource Usage", "Application lifecycle", "Energy impact", "Organizational"};

        EntityManager em = emf.createEntityManager();
        Query q0 = em.createQuery("SELECT c FROM Component c WHERE c.category = :cat");
        q0.setParameter("cat", "Activity");    

        List<Component> applicationIds = q0.getResultList();
        
        for (Component c : applicationIds) {

            //String classe = componentsId[i];

            tree.addItem(c.getId());
            tree.setChildrenAllowed(c.getId(), true);

            //EntityManager em = emf.createEntityManager();
          //  Query q = em.createQuery("SELECT c FROM Component c WHERE c.category = :cat ORDER BY c.id");
          //  q.setParameter("cat", category);                        

          //  List<Component> componentsList = q.getResultList();

          //  for (Component cc : componentsList) {

          //      tree.addItem(cc.getId());
          //      tree.setItemCaption(cc.getId(), cc.getId());
          //      tree.setParent(cc.getId(), category);
          //      tree.setChildrenAllowed(cc.getId(), true);


                Query queryInstances = em.createQuery("SELECT DISTINCT i FROM GpiKpiInstance i WHERE i.idComponent = :componentx");
                queryInstances.setParameter("componentx", c);
                List<GpiKpiInstance> instances = queryInstances.getResultList();

                for (GpiKpiInstance instance : instances) {

                    tree.addItem(c.getId() + "-" + instance.getIdGPIKPI().getId());
                    tree.setItemCaption(c.getId() + "-" + instance.getIdGPIKPI().getId(), instance.getIdGPIKPI().getName());
                    tree.setParent(c.getId() + "-" + instance.getIdGPIKPI().getId(), c.getId());
                    tree.setChildrenAllowed(c.getId() + "-" + instance.getIdGPIKPI().getId(), false);
                }



            //}
            //tree.expandItemsRecursively(category);

        }

        // Set multiselect mode
        tree.setMultiSelect(true);
        tree.setImmediate(true);

        emf.close();

        return tree;        
        
        
    }

    
    private Tree createSystemTree() {

        /**
        Tree tree = new Tree("Application");
        for (int i = 0; i < 3; i++) {
            String classe = "service " + i;
            tree.addItem(classe);
            tree.setChildrenAllowed(classe, true);
            for (int j = 0; j < 4; j++) {
                String indicator = "indicator " + i + "," + j;
                tree.addItem(indicator);
                tree.setParent(indicator, classe);
            }
            tree.expandItemsRecursively(classe);
        }
        // Set multiselect mode
        tree.setMultiSelect(true);
        tree.setImmediate(true);
        return tree;
        **/
        
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        Tree tree = new Tree("Components");
        tree.setMultiSelect(true);

        // get components list from epkb
        
        //String[] componentsId = {"IT Resource Usage", "Application lifecycle", "Energy impact", "Organizational"};

        EntityManager em = emf.createEntityManager();
        Query componentsCategory = em.createQuery("SELECT DISTINCT c.category FROM Component c ORDER BY c.category");

        List<String> catList = componentsCategory.getResultList();
        
        for (String category : catList) {

            //String classe = componentsId[i];

            tree.addItem(category);
            tree.setChildrenAllowed(category, true);

            //EntityManager em = emf.createEntityManager();
            Query q = em.createQuery("SELECT c FROM Component c WHERE c.category = :cat ORDER BY c.id");
            q.setParameter("cat", category);                        

            List<Component> componentsList = q.getResultList();

            for (Component cc : componentsList) {

                tree.addItem(cc.getId());
                tree.setItemCaption(cc.getId(), cc.getId());
                tree.setParent(cc.getId(), category);
                tree.setChildrenAllowed(cc.getId(), true);


                Query queryInstances = em.createQuery("SELECT DISTINCT i FROM GpiKpiInstance i WHERE i.idComponent = :componentx");
                queryInstances.setParameter("componentx", cc);
                List<GpiKpiInstance> instances = queryInstances.getResultList();

                for (GpiKpiInstance instance : instances) {

                    tree.addItem(cc.getId() + "-" + instance.getIdGPIKPI().getId());
                    tree.setItemCaption(cc.getId() + "-" + instance.getIdGPIKPI().getId(), instance.getIdGPIKPI().getName());
                    tree.setParent(cc.getId() + "-" + instance.getIdGPIKPI().getId(), cc.getId());
                    tree.setChildrenAllowed(cc.getId() + "-" + instance.getIdGPIKPI().getId(), false);
                }



            }
            //tree.expandItemsRecursively(category);

        }

        // Set multiselect mode
        tree.setMultiSelect(true);
        tree.setImmediate(true);

        emf.close();

        return tree;        
        

    }

    private boolean getQueryForServer(String category, String server) {


        boolean result = false;

        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        EntityManager em = emf.createEntityManager();
        
        emf.close();
        
        return result;
        
    }
}
